<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      border-collapse: collapse;
    }
  </style>
</head>
<body>
  <div id="app">
    <table border="1">
      <thead>
        <tr>
          <th>名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>小结</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(phone, index) in cart">
          <td>{{phone.name}}</td>
          <td>{{phone.price}}元</td>
          <!-- <td>{{phone.num}}</td> -->
          <td><input type="text" v-model.number="phone.num"></td>
          <!-- Number.toFixed(2)保留2位小数 -->
          <td>{{ (phone.price * phone.num).toFixed(2) }}元</td>
        </tr>
        <tr>
          <td colspan="2">总计</td>
          <td>{{totalNum()}}件</td>
          <td>{{totalPrice()}}元</td>
        </tr>
      </tbody>
    </table>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        cart: [
          {
            name: 'iphone 12',
            price: 4999,
            num: 1
          },
          {
            name: 'huawei p40 pro',
            price: 4699,
            num: 7
          },
          {
            name: 'mi 10',
            price: 4199,
            num: 6
          }
        ]
      },
      methods: {
        // 计算总数量
        totalNum() {
          let num = 0;
          this.cart.forEach(element => {
            num += element.num;
          });
          return num
        },
        // 计算总金额
        totalPrice() {
          let num = 0;
          this.cart.forEach(element => {
            num += element.num * element.price;
          });
          return num
        },
      },
    })
  </script>
</body>
</html>